package com.mediacenter.activity;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.mediacenter.R;
import com.mediacenter.application.MApplication;
import com.mediacenter.site.model.Show;
import com.mediacenter.site.model.Video;
import com.mediacenter.site.model.VideoPath;
import com.mediacenter.widget.ProgressManager;
import com.naduolai.android.ui.button.AttrToggleButton;
import com.naduolai.android.ui.button.AttrToggleButton.OnItemCheckedListiner;
import com.naduolai.android.ui.dialog.StandardAlertDialog;
import com.naduolai.android.ui.tip.NDToast;
import com.naduolai.android.util.CacheUtil;
import com.naduolai.android.util.StringUtil;
import com.ndjh.ormlite.NDJHBaseDao;
import com.umeng.analytics.MobclickAgent;

/**
 * 节目详细信息页面
 * @author lichuan
 */
public class DetailsActivity extends Activity implements OnClickListener,OnItemCheckedListiner {

	private ImageView thumb;
	private TextView director;
	private TextView performer;
	private TextView videoCount;
	private TextView detail_layout_video_years;
	private TextView title;
	private TextView description;
	private Button btn_play;
	private Button detail_btn_replay;
	private AttrToggleButton btn_collection;
	
	/**
	 * 清晰度选择按钮
	 */
	private Button btn_quality;
	
	/**
	 * 剧集列表
	 */
	private ListView detail_listView;
	
	private ImageView detail_image_logo;
	
	private Bitmap bitmap;
	
	/**
	 * 判断图片是否已下载
	 */
	private boolean downloadImage = true;
	
	/**
	 * 清晰度选择按钮
	 */
	private final int btn_quality_chooser = 10001;
	
	/**
	 * 清晰度选择框
	 */
	private PopupWindow qualityPopupWindow;
	
	/**
	 * 当前节目信息
	 */
	private Show currentShow;
	private MApplication application;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		application = MApplication.getInstance();
		ProgressManager.getInstance().setActivity(this);
		setContentView(R.layout.detail_layout);
		detail_listView = (ListView)findViewById(R.id.detail_listView);
		detail_image_logo = (ImageView)findViewById(R.id.detail_image_logo);
		title = (TextView) findViewById(R.id.detail_layout_title);
		director = (TextView) findViewById(R.id.detail_layout_director);
		performer = (TextView) findViewById(R.id.detail_layout_performer);
		detail_layout_video_years = (TextView) findViewById(R.id.detail_layout_video_years);
		thumb = (ImageView) findViewById(R.id.detail_layout_thumb);
		videoCount = (TextView) findViewById(R.id.detail_layout_video_count);
		description = (TextView) findViewById(R.id.detail_layout_description);

		detail_btn_replay = (Button) findViewById(R.id.detail_btn_replay);
		btn_play = (Button) findViewById(R.id.detail_btn_play);
		btn_collection = (AttrToggleButton) findViewById(R.id.detail_btn_collection);
		btn_quality = (Button) findViewById(R.id.detail_btn_quality);

		btn_play.setOnClickListener(this);
		detail_btn_replay.setOnClickListener(this);
		btn_collection.setOnItemCheckedListiner(this);
		btn_quality.setOnClickListener(this);
		
		currentShow = application.getCurrentShow();
		if(currentShow == null){
			//TODO  找不到节目信息处理规则
		}
		try {
			if (application.getCurrentSource().getLogo() != null) {
				thumb.setImageBitmap(bitmap);
			}
			if (application.getCurrentSource().getLogo() != null) {
				detail_image_logo.setImageBitmap(application.getCurrentSource().getLogo());
			}
			// 同步本地数据
			NDJHBaseDao<Show, Integer> showDao = MApplication.getInstance().getHelper().getShowDao();
			Show localShow = showDao.queryData("select * from Show where showid = '" + currentShow.getShowid() + "' and sourceName = '"
					+ currentShow.getSourceName() + "';");
			if (localShow != null) {
				currentShow.setLastPlayTime(localShow.getLastPlayTime());
				currentShow.setLastVideoIndex(localShow.getLastVideoIndex());
				currentShow.setLastProgress(localShow.getLastProgress());
				currentShow.setCurrentQuality(localShow.getCurrentQuality());
				currentShow.setCollected(localShow.isCollected());
				currentShow.setCollectedTime(localShow.getCollectedTime());
			}
			if (StringUtil.isNull(currentShow.getVideos()) || StringUtil.isNull(currentShow.getVideos().get(0).getVideoPaths())
					|| (System.currentTimeMillis() - currentShow.getLastUpdateTime()) / 1000 / 60 > 30) {
				VideoDetailLoader videoPathLoader = new VideoDetailLoader();
				videoPathLoader.execute(currentShow);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			showAlertDialog("警告", "非常抱歉,获取视频信息失败!", onCancelListener);
		}

	}

	

	/**
	 * 后台任务抓取视频详细信息
	 * 
	 */
	private class VideoDetailLoader extends AsyncTask<Show, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(Show... params) {
			try {
				// 网络读取剧集列表信息
				currentShow = application.getCurrentSource().getVideos(application.getCurrentShow());
				if (!StringUtil.isNull(currentShow.getVideos())) {
					// 读取第一集视频源地址
					List<VideoPath> videoPaths = currentShow.getVideos().get(0).getVideoPaths();
					if (StringUtil.isNull(videoPaths)) {
						videoPaths = application.getCurrentSource().getVideoPaths(currentShow.getVideos().get(0));
						if (!StringUtil.isNull(videoPaths)) {
							currentShow.setLastUpdateTime(System.currentTimeMillis());
							return true;
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return false;
		}
		
		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			ProgressManager.getInstance().cancel();
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			//TODO 返回HTML页面的内容
			ProgressManager.getInstance().cancel();
			if (result) {
				if (currentShow != null && !StringUtil.isNull(currentShow.getVideos())) {
					// 读取第一集视频源地址
					List<VideoPath> videoPaths = currentShow.getVideos().get(0).getVideoPaths();
					if (!StringUtil.isNull(videoPaths)) {
						initContextView();
					}
				}
			} else {
				// TODO 错误信息处理
				showAlertDialog("警告", "非常抱歉,获取视频信息失败!", onCancelListener);
			}
		}
		
		@Override
		protected void onPreExecute() {
			//TODO 任务启动，可以在这里显示一个对话框，这里简单处理
			ProgressManager.getInstance().showProcessDialog("加载中...");
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			 //TODO 更新进度
			super.onProgressUpdate(values);
		}

	};
	
	/**
	 * 后台任务抓取视频详细信息
	 * 
	 */
	private class CoverImageLoader extends AsyncTask<Show, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(Show... params) {
			try {
				CacheUtil.urlBinaryFileCopyForce(currentShow.getThumb());
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return false;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO 返回HTML页面的内容
			ProgressManager.getInstance().cancel();
			if (result) {
				bitmap = BitmapFactory.decodeFile(CacheUtil.getLocalPath(currentShow.getThumb()));
				thumb.setImageBitmap(bitmap);
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO 任务启动，可以在这里显示一个对话框，这里简单处理
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO 更新进度
			super.onProgressUpdate(values);
		}
	};
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		currentShow = application.getCurrentShow();
		if (currentShow != null && !StringUtil.isNull(currentShow.getVideos()) && !StringUtil.isNull(currentShow.getVideos().get(0).getVideoPaths())) {
			initContextView();
		}
	}
	
	/**
	 * 初始化视图
	 */
	private boolean initContextView(){
		try {
			if (currentShow == null) {
				currentShow = application.getCurrentShow();
			}
			if (currentShow == null) {
				return false;
			}
			System.err.println("initContextView.currentShow: " + currentShow);
			String descript = TextUtils.isEmpty(currentShow.getDescription()) ? "" : currentShow.getDescription();
			btn_collection.setTurnOn(currentShow.isCollected());
			title.setText(currentShow.getTitle());
			videoCount.setText((currentShow.getVideos() == null ? "" : currentShow.getVideos().size()) + "");
			description.setText("      " + descript);
			director.setText(currentShow.getDirectors());
			performer.setText(currentShow.getPerformers());
			if (!StringUtil.isNull(currentShow.getPublished())) {
				detail_layout_video_years.setText(currentShow.getPublished().length() > 4 ? currentShow.getPublished().subSequence(0, 4)
						: currentShow.getPublished());
			}
			List<Video> videos = currentShow.getVideos();
			if (videos != null && videos.size() > 1) {
				btn_play.setVisibility(View.GONE);
				detail_listView.setAdapter(new VideoListAdapter(videos));
				detail_listView.setOnItemClickListener(onItemClickListener);
				if (currentShow.getLastPlayTime() <= 0) {
					detail_listView.requestFocus();
					detail_listView.setSelection(0);
				} 
			} else if (videos != null && videos.size() == 1) {
				btn_play.setVisibility(View.VISIBLE);
				if (currentShow.getLastPlayTime() <= 0) {
					btn_play.requestFocus();
				}
			}
			if (currentShow.getLastPlayTime() > 0) {
				detail_btn_replay.setVisibility(View.VISIBLE);
				detail_btn_replay.requestFocus();
			}
			if (!StringUtil.isNull(videos) &&  !StringUtil.isNull(videos.get(0).getVideoPaths())) {
				btn_play.setVisibility(View.VISIBLE);
				btn_quality.setVisibility(View.VISIBLE);
				btn_collection.setVisibility(View.VISIBLE);
				btn_quality.setBackgroundResource(R.drawable.normal_btn_selector);
				btn_play.setBackgroundResource(R.drawable.normal_btn_selector);
				//btn_quality.setText(videos.get(0).getVideoPaths().get(0).getQuality());
				if (videos.get(0).getVideoPaths().size() == 1) {
					btn_quality.setEnabled(false);
					btn_quality.setFocusable(false);
				}
			}else{
				return false;
			}
			List<VideoPath> videoPaths = videos.get(0).getVideoPaths();
			String quality = currentShow.getCurrentQuality();
			if (StringUtil.isNull(quality)) {
				quality = videoPaths.get(0).getQuality();
				currentShow.setCurrentQuality(quality);
				application.getHelper().getShowDao().update(currentShow);
			}
			System.err.println("videoPaths.get(0).getQuality(): " + quality);
			btn_quality.setText(quality);
			 
			//设置缩略图
			if(!StringUtil.isNull(currentShow.getThumb())){
				bitmap = BitmapFactory.decodeFile(CacheUtil.getLocalPath(currentShow.getThumb()));
				if (bitmap != null) {
					thumb.setImageBitmap(bitmap);
				} else {
					CoverImageLoader coverImageLoader = new CoverImageLoader();
					coverImageLoader.execute(currentShow);
					return false;
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 初始化按钮组件
	 * @return
	 */
	private boolean initButtonLayout(){
		List<Video> videos = currentShow.getVideos();
		if (currentShow.getLastPlayTime() > 0) {
			detail_btn_replay.setVisibility(View.VISIBLE);
		}
		if (StringUtil.isNull(videos) || StringUtil.isNull(videos.get(0).getVideoPaths())) {
			btn_quality.setBackgroundResource(R.drawable.btn_focus);
			btn_play.setBackgroundResource(R.drawable.btn_focus);
			btn_quality.setEnabled(false);
			btn_play.setEnabled(false);
			//TODO 提醒用户，没法获取到视频播放地址
			return false;
		}else{
			btn_quality.setBackgroundResource(R.drawable.normal_btn_selector);
			btn_play.setBackgroundResource(R.drawable.normal_btn_selector);
			btn_quality.setText(videos.get(0).getVideoPaths().get(0).getQuality());
			btn_quality.setEnabled(true);
			if (videos.get(0).getVideoPaths().size() == 1) {
				btn_quality.setEnabled(false);
				btn_quality.setFocusable(false);
			}
			btn_play.setEnabled(true);
		}
		return true;
	}
	
	/**
	 * 剧集列表点击事件
	 */
	private OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			Intent intent = new Intent(DetailsActivity.this, VideoActivity.class);
			intent.putExtra(VideoActivity.INTENT_PARAMATER_VIDEO, true);
			intent.putExtra(VideoActivity.INTENT_PARAMATER_VIDEO_INDEX, position);
			startActivity(intent);
			
		}
	};

	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.detail_btn_play:
			Intent intent = new Intent(DetailsActivity.this, VideoActivity.class);
			intent.putExtra(VideoActivity.INTENT_PARAMATER_VIDEO, true);
			intent.putExtra(VideoActivity.INTENT_PARAMATER_VIDEO_INDEX, 0);
			intent.putExtra("fromStart", true);
			
			startActivity(intent);
			
			break;
		case R.id.detail_btn_replay:
			intent = new Intent(DetailsActivity.this, VideoActivity.class);
			intent.putExtra(VideoActivity.INTENT_PARAMATER_VIDEO, true);
			intent.putExtra(VideoActivity.INTENT_PARAMATER_VIDEO_INDEX, currentShow.getLastVideoIndex());
			intent.putExtra(VideoActivity.INTENT_PARAMATER_VIDEO_PATH_INDEX, currentShow.getLastPathIndex());
			intent.putExtra(VideoActivity.INTENT_PARAMATER_VIDEO_PROGRESS, currentShow.getLastProgress());
			startActivity(intent);
			break;
		case R.id.detail_btn_quality:
			toggleQualityPopupWindow(v);
			break;
		case btn_quality_chooser:
			String quality = ((Button) v).getText().toString();
			btn_quality.setText(quality);
			currentShow.setCurrentQuality(quality);
			toggleQualityPopupWindow(null);
			break;
		default:
			break;
		}
	}

	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (detail_listView.isFocused()) {
			if (keyCode == KeyEvent.KEYCODE_DPAD_UP
					&& detail_listView.getSelectedItemPosition() > 0) {
				detail_listView.setSelection(detail_listView
						.getSelectedItemPosition() - 1);
				return true;
			} else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN
					&& detail_listView.getSelectedItemPosition() < detail_listView
							.getCount() - 1) {
				detail_listView.setSelection(detail_listView
						.getSelectedItemPosition() + 1);
				return true;
			}
		}
				
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onBackPressed() {
		if (qualityPopupWindow != null && qualityPopupWindow.isShowing()) {
			qualityPopupWindow.dismiss();
			return;
		}
		super.onBackPressed();
	}
	
	/**
	 * 剧集列表代理器
	 */
	private class VideoListAdapter extends BaseAdapter {
		
		private List<Video> videoList;
		
		public VideoListAdapter(List<Video> videoPaths) {
			this.videoList = videoPaths;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LinearLayout itemLayout = (LinearLayout) convertView;
			TextView itemText;
			if(itemLayout == null){
				itemLayout = new LinearLayout(DetailsActivity.this);
				itemLayout.setPadding(0, 5, 0, 5);
				itemLayout.setBackgroundResource(R.drawable.bar_default);
				itemLayout.setGravity(Gravity.CENTER_VERTICAL);
				itemText = new TextView(DetailsActivity.this);
				itemText.setTextColor(Color.WHITE);
				itemText.setSingleLine();
				itemText.setLines(1);
				itemText.setEllipsize(TruncateAt.END);
				itemText.setHorizontallyScrolling(true);
				itemText.setTextSize(24.f);
				itemText.setPadding(25, 0, 0, 0);
				itemLayout.addView(itemText);
			}else{
				itemText = (TextView) itemLayout.getChildAt(0);
			}
			if (currentShow.getLastPlayTime() <= 0 && position == 0) {
				itemLayout.setSelected(true);
				itemLayout.requestFocus();
			}
			
			itemText.setText(videoList.get(position).getTitle());
			
			return itemLayout;
		}
		
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return videoList.size();
		}
	};

	/**
	 * 切换显示清晰度选择框
	 */
	private void toggleQualityPopupWindow(View v){
		if (qualityPopupWindow == null) {
			LinearLayout rootLayout = new LinearLayout(this);
			rootLayout.setBackgroundResource(R.drawable.bg_out);
			rootLayout.setOrientation(LinearLayout.VERTICAL);
			List<VideoPath> videoPaths = currentShow.getVideos().get(0).getVideoPaths();
			if (videoPaths.size() > 1) {
				int init_height = 55;
				LinearLayout.LayoutParams seperatorParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
				seperatorParams.topMargin = 5;
				seperatorParams.bottomMargin = 5;
				LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 55);
				for (int i = 0; i < videoPaths.size(); i++) {
					Button button = new Button(this);
					button.setId(btn_quality_chooser);
					button.setTextColor(Color.WHITE);
					button.setTextSize(26.f);
					button.setText(videoPaths.get(i).getQuality());
					button.setBackgroundResource(R.drawable.menu_btn_selector);
					button.setOnClickListener(this);
					rootLayout.addView(button, buttonParams);
					if(i < videoPaths.size() -1){
						LinearLayout seperator = new LinearLayout(this);
						seperator.setBackgroundResource(R.drawable.line);
						seperator.setFocusable(false);
						rootLayout.addView(seperator, seperatorParams);
						init_height += 60;
					}else{
						init_height += 55;
					}
				}
				qualityPopupWindow = new PopupWindow(rootLayout, 220, init_height);
				qualityPopupWindow.setBackgroundDrawable(new BitmapDrawable());
				qualityPopupWindow.setOutsideTouchable(true);
				qualityPopupWindow.setFocusable(true);
//				qualityPopupWindow.setOutsideTouchable(false);
			}
		}
		if (qualityPopupWindow != null) {
			if (qualityPopupWindow.isShowing()) {
				qualityPopupWindow.dismiss();
			} else if (v != null) {
				int measureWidth = v.getMeasuredWidth();
				if (measureWidth > 0) {
					qualityPopupWindow.showAsDropDown(v, -(220 - measureWidth) / 2, 0);
				} else {
					qualityPopupWindow.showAsDropDown(v);
				}
				ViewGroup qualityLayout = ((ViewGroup) qualityPopupWindow.getContentView());
				qualityLayout.requestFocus();
				String quality = currentShow.getCurrentQuality();
				for (int i = 0; i < qualityLayout.getChildCount(); i++) {
					View childButton = qualityLayout.getChildAt(i);
					if (childButton instanceof Button && ((Button) childButton).getText().equals(quality)) {
						childButton.requestFocus();
						childButton.setSelected(true);
						break;
					}
				}
			}
		}
	}
	
	
	@Override
	protected void onDestroy() {
		if (bitmap != null && !bitmap.isRecycled()) {
			bitmap.recycle();
		}
		super.onDestroy();
	}

	@Override
	public void onItemChecked(boolean checked) {
		try {
			NDJHBaseDao<Show, Integer> showDao = MApplication.getInstance().getHelper()
					.getShowDao();
			Show show = showDao.queryData("select * from Show where showid = '" + currentShow.getShowid()
					+ "' and sourceName = '" + currentShow.getSourceName() + "';");
			currentShow.setCollected(checked);
			currentShow.setCollectedTime(new Timestamp(System.currentTimeMillis()));
			show.setCollected(checked);
			show.setCollectedTime(currentShow.getCollectedTime());
			showDao.update(show);
			if (checked) {
				NDToast.makeTextShow(DetailsActivity.this, "收藏成功!", Toast.LENGTH_SHORT);
				//视频被收藏的次数
				MobclickAgent.onEvent(DetailsActivity.this, "VIDEO_FAVORITE_COUNT", currentShow.getTitle());
			} else {
				NDToast.makeTextShow(DetailsActivity.this, "取消收藏", Toast.LENGTH_SHORT);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	OnCancelListener onCancelListener = new OnCancelListener() {
		@Override
		public void onCancel(DialogInterface dialog) {
			System.err.println("onCancel");
			finish();
		}
	};
	
	/**
	 * 显示消息提示框,然后只给用户确定按钮
	 * @param title 
	 * @param message
	 */
	protected void showAlertDialog(String title,String message, OnCancelListener onCancelListener) {
		try {
			if(isFinishing()){
				return;
			}
			StandardAlertDialog.Builder ndAlertDialog = new StandardAlertDialog.Builder(DetailsActivity.this);
			ndAlertDialog.setTitle(title);
			ndAlertDialog.setMessage(message);
			ndAlertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			StandardAlertDialog dialog = ndAlertDialog.create();
			dialog.setOnCancelListener(onCancelListener);
			dialog.show();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
